package com.jy.modules.cims.component.loan;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.FileUtils;
import com.jy.modules.cims.common.sysUtils.IFTPClient;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.component.common.service.TCMmQuotaRetrunService;
import com.jy.modules.cims.component.image.TransferImagesHelper;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.dao.ImgurlDao;
import com.jy.modules.cims.data.dto.ImgurlDto;
import com.jy.modules.cims.data.dto.PlcImagesDto;
import com.jy.modules.cims.data.dto.credit.CreditImageInformationDto;
import com.jy.modules.cims.sysUtils.ImgurFtpConfigInfo;
/**
 * 影像资料上传升级版本 plus
 * ClassName: CloanImagesFileImplPlus 
 * @Description: TODO
 * @author dell
 * @date 2015-11-13
 */
@Service("com.jy.modules.cims.component.loan.CloanImagesFileImplPlus")
public class CloanImagesFileImplPlus {

	private static Logger logger = LoggerFactory.getLogger(CloanImagesFileImplPlus.class);
	
	private String FTP_COMPRESSED_YES = "Y";
	private String Result_Status = "Result_Status";
	
	
	
	
	@Autowired
	public ImgurlDao imgurlDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.CLoanImpl")
	private ICLoan cLoan;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
	private TCMmLoanDetailService tcmmLoanDetailService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
	private TCMmCreditDetailService tcmmCreditDetailService;
	

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmQuotaRetrunService")
	private TCMmQuotaRetrunService tcmmQuotaRetrunService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.image.TransferImagesHelper")
	private TransferImagesHelper transferImagesHelper;
	
	public void doImgByPlcImages(final PlcImagesDto plcDto){
		
		/**
		 * 验证参数是否合法
		 */
		if(!SimpleStringUtils.hasText(plcDto.getDealType())
				||!SimpleStringUtils.hasText(plcDto.getContractNo())
				||!SimpleStringUtils.hasText(plcDto.getCooperorgCode())
				||!SimpleStringUtils.hasText(plcDto.getDealCode())
				//||!StringUtils.hasText(plcDto.getProductType())
				||plcDto.getDealDate()==null){
			logger.info("影像上传数据参数不完整！机构编号：{}，交易流水：{}，合同号：{}，业务类型：{}，交易日期：{}"
					,plcDto.getCooperorgCode(),plcDto.getDealCode(),plcDto.getContractNo(),plcDto.getDealType(),DateTimeUtils.formatDate(plcDto.getDealDate(),"yyyy-MM-dd" ));
			return;
		}
		
		/**
		 * 根据，机构编码，业务类型，贷款类型，获取配置的影像资料类型。
		 * 调用振环的方法，组装个影像资料类型如："'A1','B1','N1'"
		 */
		try {
			String attachNames = null;
			List<CreditImageInformationDto> list = tcmmQuotaRetrunService.queryDataToWn(plcDto);
			if(CollectionsUtils.isNotEmpty(list)&&list.get(0)!=null){
				attachNames = list.get(0).getDictDetailValue();
				attachNames = "'"+attachNames.replace(",", "','")+"'";
			}
			/**
			 * 根据机构编码，合同号，业务类型，贷款类型，获取需要上传的影像资料列表
			 */
			List<ImgurlDto> imgList = cLoan.searchUploadImgurls(plcDto.getContractNo(), attachNames);
			if(CollectionsUtils.isEmpty(imgList)){
				logger.info("交易流水号：{}，业务类型：{}，贷款类型：{}，合同号:{}没有需要上传的影像资料",plcDto.getDealCode(),plcDto.getDealType(),plcDto.getProductType(),plcDto.getContractNo());
				return ;
			}
			plcDto.setImgList(imgList);
		} catch (Exception e1) {
			e1.printStackTrace();
			logger.error("交易流水号：{}，业务类型：{}，贷款类型：{}，合同号:{}，获取影像配置信息或者获取影像列表异常！", plcDto.getDealCode(),plcDto.getDealType(),plcDto.getProductType(),plcDto.getContractNo());
		}
		
		
		/**
		 * 获取ftp配置信息,根据合同号处理上传文件
		 */
		IFTPClient ftpClient = null;
		Map<String,String> resultMap = null;
		try {
			ImgurFtpConfigInfo imgurFtpConfigInfo = transferImagesHelper.getImgurFtpConfigInfoByCpcBizLoanType(plcDto.getCooperorgCode(),plcDto.getDealType(),plcDto.getProductType(),plcDto.getContractNo());
			ftpClient = transferImagesHelper.getFTPClient(imgurFtpConfigInfo);
			// 登录FTP不成功直接返回
			if (!transferImagesHelper.loginFTP(ftpClient)) {
				return;
			}
			//创建临时目录：如果没有才创建
			transferImagesHelper.createTempDir(imgurFtpConfigInfo.getTmpFilePath());
			List<String> successContractList = new ArrayList<String>();
			resultMap = transferImgByContractNo(ftpClient, successContractList, imgurFtpConfigInfo,plcDto);
			successContractList = null;	
			logger.info("流水号:{},合同号:{},处理状态:{}", plcDto.getDealCode(), plcDto.getContractNo(), resultMap.get(Result_Status));
		} catch (Exception e) {
			logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e);
		}finally{
			//退出登录
			transferImagesHelper.logOutFTP(ftpClient);
			//删除临时目录文件
			if(resultMap!=null&&resultMap.containsKey(CimsConstant.DIR_TEMP_FILE))
				FileUtils.deleteDirectory(resultMap.get(CimsConstant.DIR_TEMP_FILE).toString());
		}
	}
	
	
	private Map<String,String> transferImgByContractNo(IFTPClient ftpClient, 
			List<String> successContractList, 
			ImgurFtpConfigInfo imgurFtpConfigInfo,
			final PlcImagesDto plcDto) throws Exception {
		//参数组装
		String contractNo = plcDto.getContractNo(); //合同号
		List<ImgurlDto> imgurlList = plcDto.getImgList();//影像列表
		String dealType = plcDto.getDealType(); //交易类型
		String packageName = plcDto.getPackageName();//包号
		String isUpdateStatus = plcDto.getIsUpdateStatus();//是否修改状态
		Date dealDate = plcDto.getDealDate();//交易日期
		
		Map<String,String> resultMap = new HashMap<String, String>();
		
		String transFileStatus = CimsConstant.DOWNLOAD_FILE_FAIL; //默认成功
		// 从url下载文件到本地
		boolean transFileflag = transferImagesHelper.downloadURLImg(imgurFtpConfigInfo, imgurlList);
		if (!transFileflag) {
			resultMap.put(Result_Status,CimsConstant.DOWNLOAD_FILE_FAIL);
			return resultMap;
		}

		String accessoryFtpUrl = "";

		// 如果上传压缩包影像文件
		if (FTP_COMPRESSED_YES.equalsIgnoreCase(imgurFtpConfigInfo.getFtpCompressed())) {
			String zipFileName = SimpleStringUtils.append(contractNo, ".zip");
			String zipDires = SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), contractNo);// 下载到当地那个路径下
			// 压缩一个合同号的影像文件
			boolean zipFile = transferImagesHelper.zipFile(zipDires, SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), zipFileName));
			if (zipFile) {
				// 上传到文件服务器的路径
				String remoteDirectoryPath = SimpleStringUtils.append(imgurFtpConfigInfo.getFtpDir(),
						DateTimeUtils.formatDate(dealDate, DateTimeUtils.DEFAULT_DATE_FORMAT), "/", packageName, "/");
				boolean uploadImg = ftpClient.uploadFile(new File(SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), zipFileName)),
						remoteDirectoryPath);
				if (uploadImg) {
					successContractList.add(contractNo);
					transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;
					accessoryFtpUrl = remoteDirectoryPath + SimpleStringUtils.append(contractNo, "_ok.zip");
					resultMap.put(CimsConstant.DIR_TEMP_FILE,imgurFtpConfigInfo.getTmpFilePath());//文件临时目录
					//resultMap.put(CimsConstant.DIR_TEMP_ZIP, StringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), zipFileName));//压缩包临时目录
				} else {
					transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
				}
			}
			ImgurlDto imgurlDto = new ImgurlDto();
			imgurlDto.setContractNo(contractNo);
			imgurlDto.setFileUploadStatus(transFileStatus);
			imgurlDao.updateImgurlFileUploadStatus(SearchParamUtil.getSearchParam(imgurlDto));
			imgurlDto = null;
		} else {
			int uploadSuccessCount = 0;
			String localDires = "";
			for (ImgurlDto imgurl : imgurlList) {
				String[] attachUrlArray = imgurl.getAttachUrl().split("/");
				String remoteFileName = attachUrlArray[attachUrlArray.length - 1];
				localDires = SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), contractNo, "/");
				String remoteDirectoryPath = SimpleStringUtils.append(imgurFtpConfigInfo.getFtpDir(), contractNo, "/");
				boolean uploadImg = ftpClient.uploadFile(new File(SimpleStringUtils.append(localDires, remoteFileName)), remoteDirectoryPath);
				if (uploadImg) {
					uploadSuccessCount++;
					transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;
					accessoryFtpUrl = remoteDirectoryPath;
				} else {
					transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
				}
			}

			int pendingSize = imgurlList.size();
			if (uploadSuccessCount == pendingSize) {
				successContractList.add(contractNo);
				transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;
				resultMap.put(CimsConstant.DIR_TEMP_FILE,imgurFtpConfigInfo.getTmpFilePath());//文件临时目录
			} else {
				transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
			}
		}
		
		
		
		// 修改贷款明细的状态发送请求查询
		if (CimsConstant.UPLOAD_FILE_SUCCESS.equals(transFileStatus)) {
			if(!"N".equals(isUpdateStatus)){
				//债权
				if(CimsConstant.DEAL_TYPE_CREDIT_OUT.equals(dealType)){
					TCMmCreditDetailDTO tcmmCreditDetailDTO = new TCMmCreditDetailDTO();
					tcmmCreditDetailDTO.setCreditCode(contractNo);
					List<TCMmCreditDetailDTO> tcmmCreditDetailList = tcmmCreditDetailService.searchTCMmCreditDetail(SearchParamUtil.getSearchParam(tcmmCreditDetailDTO));
					if(CollectionsUtils.isNotEmpty(tcmmCreditDetailList)){
						for (TCMmCreditDetailDTO newTcMmCreditDetailDTO : tcmmCreditDetailList) {
							newTcMmCreditDetailDTO.setCreditEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);
							newTcMmCreditDetailDTO.setAccessoryFtpUrl(accessoryFtpUrl);
							newTcMmCreditDetailDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));
							tcmmCreditDetailService.updateTCMmCreditDetail(newTcMmCreditDetailDTO);
						}
					}
				}
				//贷款
				if(CimsConstant.DEAL_TYPE_LOAN_OUT.equals(dealType)){
					TCMmLoanDetailDTO tcmmLoanDetailDTO = new TCMmLoanDetailDTO();
					tcmmLoanDetailDTO.setContractNo(contractNo);
					List<TCMmLoanDetailDTO> tcmmLoanDetailList = tcmmLoanDetailService
							.searchTCMmLoanDetail(SearchParamUtil.getSearchParam(tcmmLoanDetailDTO));
					if (CollectionsUtils.isNotEmpty(tcmmLoanDetailList)) {
						for (TCMmLoanDetailDTO newTCMmLoanDetailDTO : tcmmLoanDetailList) {
							newTCMmLoanDetailDTO.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);
							newTCMmLoanDetailDTO.setAccessoryFtpUrl(accessoryFtpUrl);
							newTCMmLoanDetailDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));
							tcmmLoanDetailService.updateTCMmLoanDetail(newTCMmLoanDetailDTO);
						}
					}
					tcmmLoanDetailDTO = null;
				}
			}else{
				logger.info("合同号{}上传成功！未修改状态！",contractNo);
			}
		}
		resultMap.put(Result_Status, transFileStatus);
		return resultMap;
	}
	
}
